package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //注入Redis实现对象
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取验证码
     *
     * @return
     */
    @GetMapping("/smscode")
//    public R sendSmsCode(String phone, HttpSession session) {
    public R sendSmsCode(String phone) {
        //生成验证码
        String code = ValidateCodeUtils.generateValidateCode4String(6);
        System.out.println("code = " + code);
        //给手机号发送验证码(这步目前做不到)
        //SMSUtils.sendMessage("签名","模板",phone,code);
        //为验证接下来用户登录时提交过来的验证码是否正确，需要把验证码保存到session域
//        session.setAttribute(phone, code);

        //把验证码存入Redis中，
        redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
        return R.success(code);
    }

    /**
     * 用户登录
     * @param map
     * @param
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
//    public R login(@RequestBody Map<String, String> map) {
        //获取用户提交的手机号和验证码
        String phone = map.get("phone");
        String code = map.get("code");
        //获取先前session域存储的验证码
//        String sessionCode = (String) session.getAttribute(phone);
//        if (sessionCode.equals(code)) {
//            User user = userService.findUser(phone);
//            if (user == null) {
//                user = new User();
//                user.setPhone(phone);
//                userService.addUser(user);
//            }
//            session.setAttribute("user", user);
//            return R.success("登录成功");
//        }
//        return R.error("验证码有误");

        //获取Redis中用户登录对象
        String coded = (String)redisTemplate.opsForValue().get(phone);
        if (coded!=null&& coded.equals(code)){
            User user = userService.findUser(phone);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.addUser(user);
            }
            session.setAttribute("user", user);
            //登录成功之后，删除redis
            redisTemplate.delete(phone);
            return R.success("登录成功");
        }
        return R.error("验证码有误");
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出登录");
    }
}
